#!/usr/bin/python
import sys 
import os
import os.path
import subprocess
import musicbrainz2.disc as mbdisc
import musicbrainzngs as mb
from utils import *

conn = dbconn()
path = sys.argv[-1]

flacpaths, cuepaths = find_flac_at_path(path)
if not flacpaths :
	raise Exception("FLAC file not found", path)
elif len(flacpaths)>1 :
	raise Exception("Multiple FLAC files found", path)

flacpath = flacpaths[0]

tags = dict(get_flac_comments(flacpath))

discid = tags["MUSICBRAINZ_DISCID"]
releaseid = tags["MUSICBRAINZ_ALBUMID"]
discnum = int(tags["DISCNUMBER"])

# check if we have already ripped it
cursor = conn.cursor()
duplicates = list(cursor.execute("select release, num, path from disc where id=?",(discid,)))
if len(duplicates)>0 :
	print "!!!! This disc may be in the library already:"
	for release, num, path in duplicates:
		print "path=%s\nrelease=%s\ndiscnum=%d" % (path, release, num)

print "registering disc..."
path = os.path.relpath(flacpath, flacdir)
store_disc_record(conn, discid, releaseid, discnum, path)
	
print "registering release..."
release = update_mbrelease(conn, releaseid)

print "Tagging FLAC file..."
comments = vorbis_comments(conn, releaseid, discid, discnum)
print set_flac_tags(flacpath, comments)

cuesheet = read_cuefile_from_flac(flacpath)
cuepath, extension = os.path.splitext(flacpath)
cuepath += ".cue"
print "Writing cuesheet... %s" % cuepath
with codecs.open(cuepath,"w","utf-8") as f :
	lines = add_metadata_to_cuefile(conn, releaseid, discnum, cuesheet)
	f.write(u"\n".join(lines))

conn.commit()
